package com.yyk.dzvisit.core.filter;

import com.yyk.dzvisit.enums.RequestContextEnum;
import com.yyk.dzvisit.vo.RequestContext;
//import com.yyk.prometheus.util.PrometheusUtil;
//import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * Description:   .
 *
 * @author : LuShunNeng
 * @date : Created in 2018/12/19 下午4:29
 */
@Slf4j
public class YykRequestFilter implements Filter {

    /**
     * 统一token前缀
     */
    private static final String TOKEN_PREFIX = "Bearer ";

    /**
     * 打点前缀
     */
    public static final String PROMETHEUS_PREFIX = "yyk-core";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
       // Timer requestLatency = PrometheusUtil.timerInit(StringUtils.join(PROMETHEUS_PREFIX, "-http-latency"), "url", request.getRequestURI());

        // traceId
        String traceId = request.getHeader(RequestContextEnum.TRACE_ID.getOutCode());
        MDC.put(RequestContextEnum.TRACE_ID.name(), traceId);
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        RequestContext requestContext = RequestContext.getContext();
        if (StringUtils.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString();
        }
        requestContext.addContextDetail(RequestContextEnum.TRACE_ID.name(), traceId);
        log.info("请求url{}:", request.getRequestURI());
        // token
        String token = request.getHeader(RequestContextEnum.HX_TOKEN.getOutCode());
        if (StringUtils.isNotBlank(token)) {
            requestContext.addContextDetail(RequestContextEnum.HX_TOKEN.name(), token.replace(TOKEN_PREFIX, ""));
        }
        log.debug("在请求处理之前生成 logback ", RequestContextEnum.TRACE_ID.name(),
                ":", traceId);

        chain.doFilter(servletRequest, response);

        stopWatch.stop();
       // requestLatency.record(stopWatch.getTime(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS);
        log.info("请求耗时：{}ms", stopWatch.getTime(TimeUnit.MILLISECONDS));
        log.debug("整个请求处理完毕清除 logback MDC");
        MDC.clear();
        RequestContext.clear();
    }

    @Override
    public void destroy() {

    }
}
